package com.yan.exceptiontest;

import java.util.Arrays;

public class Test2 {
    public static void main(String[] args) {
        int[] a = {4,7,3,4,5,1,9,8,11,12,6,18,10,2};
        sort(a);
        System.out.println(Arrays.toString(a));
        int binarySearch = binarySearch(a , 12);
        System.out.println("数值12的的索引为" + binarySearch);
    }

    public static void sort(int[] arr){
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = 0; j < arr.length - 1 - i; j++) {
                if(arr[j] > arr[j + 1]){
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }

    public static int binarySearch(int[] arr , int num){
        int min = 0 , max = arr.length - 1;
        int mid;
        int index = -1;
        while(true){
            mid = (min + max) / 2;
            if(arr[mid] < num){
                min = mid + 1;
            } else if(arr[mid] > num){
                max = mid - 1;
            } else {
                index =  mid;
                return index;
            }
            if(min > max){
                break;
            }
        }
        return min - max;
    }
}
